<template>
<!-- 账号和安全页面 -->
    <div>
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>账号和安全</span>
          </div>
          <div class="boxx">
            <div class="box-1">
              <div class="box-2">
                <p class="p1" style="font-size: 20px">手机绑定</p>
              </div>
              <p class="p2">
                {{tableDate.phone}}<span><el-button type="text" class="xg" @click="openUpdatePhone()">{{bindPhone}}</el-button></span>
              </p>
            </div>
            <div class="box-1">
              <div class="box-2">
                <p class="p1" style="font-size: 20px">邮箱绑定</p>
              </div>
              <p class="p2">
                {{tableDate.email}}<span><el-button type="text" class="xg" @click="openUpdateEmail()">{{bindEmail}}</el-button></span>
              </p>
            </div>
          </div>
        </el-card>
        <!-- 手机号,邮箱弹窗 -->
        <el-dialog
          :title='title'
          :visible.sync="updatePhoneAndEmailDialogVisible"
          width="30%"
          style="margin-top:100px"
          :before-close="closeExpertFormDialog"
          :append-to-body="shouldAppendToBody" >
            <el-form :model="form" :rules="updateRules" ref="form">
              <el-form-item label="手机号" prop="phone" style="width:300px" v-show="v_show_phone">
                <el-input v-model="form.phone" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="邮箱" prop="email" style="width:300px" v-show="v_show_email">
                  <el-input v-model="form.email" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="cancel('form')">取 消</el-button>
            <el-button type="primary" @click="updatePhone('form')">确 定</el-button>
          </span>
        </el-dialog>

    </div>
</template>
<script>
export default {
  name: 'AccountAndSecurity',
  data () {
    return {
      // 修改手机号，邮箱表单规则
      updateRules: {
        phone: [{ validator: this.validatorPhone, trigger: 'blur' }],
        email: [{ validator: this.validatorEmail, trigger: 'blur' }]
      },
      // 邮箱是否绑定
      bindEmail: '',
      // 电话是否绑定
      bindPhone: '',
      // v-show电话输入框
      v_show_phone: false,
      // v-show邮箱输入框
      v_show_email: false,
      // 弹窗标题名称
      title: '',
      // 修改邮箱弹窗
      updateEmailDialogVisible: false,
      // 查询个人信息
      tableDate: {},
      // 修改电话弹窗
      updatePhoneAndEmailDialogVisible: false,
      // 是否将弹窗插入至 body 元素。默认将弹窗插入至 body 元素
      shouldAppendToBody: false,
      // 手机和邮箱表单数据
      form: {
        phone: '',
        email: ''
      }
    }
  },
  mounted () {
    // 根据当前登录的用户id查询用户信息
    this.selectUserbyId()
  },
  methods: {
    // 验证邮箱格式，其他用户是否绑定
    validatorEmail (email, value, callback) {
      // 验证邮箱的正则表达式
      // 以非空字符开头（^[^\s@]+）；包含一个 @ 符号（@）； 在 @ 符号后面至少有一个非空字符（`[
      const reg = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
      if (value !== '') {
        if (!reg.test(value)) {
          callback(new Error('输入正确邮箱'))
        } else {
          this.$axios.get('/user/selectUserByEmail?email=' + value).then(res => {
            if (res.data.data !== null) {
              if (value === this.tableDate.email) {
                callback()
              } else {
                callback(new Error('当前邮箱已存在'))
              }
            } else {
              callback()
            }
          })
        }
      } else {
        callback()
      }
    },
    // 验证手机号格式，其他用户是否绑定
    validatorPhone (phone, value, callback) {
      // 验证手机号的正则表达式
      const reg = /^(((13[0-9]{1})|(15[0-9]{1})|(16[0-9]{1})|(17[3-8]{1})|(18[0-9]{1})|(19[0-9]{1})|(14[5-7]{1}))+\d{8})$/
      if (value !== '') {
        if (!reg.test(value)) {
          callback(new Error('输入正确手机号'))
        } else {
          this.$axios.get('/user/selectUserByPhone?phone=' + value).then(res => {
            if (res.data.data !== null) {
              if (value === this.tableDate.phone) {
                callback()
              } else {
                callback(new Error('当前手机号已存在'))
              }
            } else {
              callback()
            }
          })
        }
      } else {
        callback()
      }
    },
    // 判断电话和邮箱是否绑定
    bind () {
      if (this.tableDate.phone === '' || this.tableDate.phone === null || this.tableDate.phone === undefined) {
        this.bindPhone = '绑定'
      } else {
        this.bindPhone = '修改绑定'
      }
      if (this.tableDate.email === '' || this.tableDate.email === null || this.tableDate.email === undefined) {
        this.bindEmail = '绑定'
      } else {
        this.bindEmail = '修改绑定'
      }
    },
    // 添加点击X关闭是清空from表单数据
    closeExpertFormDialog (done) {
      // 刷新form表单验证规则
      this.$refs.form.resetFields()
      // done 用于关闭 Dialog
      done()
      this.message('info', '已取消修改昵称')
    },
    // 修改电话
    updatePhone (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const formData = new FormData()
          formData.set('id', this.tableDate.id)
          formData.set('phone', this.form.phone)
          formData.set('email', this.form.email)
          this.$axios.put('/user/updateUserByLoginNameById', formData)
            .then(res => {
              if (res.status === 200) {
                this.updatePhoneAndEmailDialogVisible = false
                this.message('success', '修改电话成功')
                this.selectUserbyId()
                // this.$eventBus.$emit('update-nickname-done')
                // console.log(this.tableDate)
              } else {
                this.message('warning', res.data.obj)
              }
            })
            .catch(() => {
              // console.log(error)
              this.message('warning', '对不起，修改失败！')
            })
        } else {
          // console.log('error submit!!')
          return false
        }
      })
    },
    // 修改邮箱和电话取消按钮
    cancel () {
      // 刷新form表单验证规则
      this.$refs.form.resetFields()
      this.updatePhoneAndEmailDialogVisible = false
      this.message('info', '已取消修改')
    },
    // 打开修改邮箱弹窗
    openUpdateEmail () {
      this.title = '邮箱'
      this.v_show_phone = false
      this.v_show_email = true
      this.form.phone = this.tableDate.phone
      this.form.email = this.tableDate.email
      this.shouldAppendToBody = true
      this.updatePhoneAndEmailDialogVisible = true
    },
    // 打开修改电话弹窗
    openUpdatePhone () {
      this.title = '电话'
      this.v_show_phone = true
      this.v_show_email = false
      this.form.phone = this.tableDate.phone
      this.form.email = this.tableDate.email
      this.shouldAppendToBody = true
      this.updatePhoneAndEmailDialogVisible = true
    },
    // 根据当前登录的用户id查询用户信息
    selectUserbyId () {
      if (localStorage.getItem('userId') !== null) {
        this.$axios.get('/user/selectUserbyId?id=' + localStorage.getItem('userId')).then(res => {
          if (res.data.flag) {
            this.tableDate = res.data.data
            // this.message('success', '获取用户个人信息成功')
            this.bind()
          } else {
            this.message('error', '获取用户信息失败,请重新登录')
          }
        }).catch(() => {
          // console.log(err)
        })
      } else {
        // console.log(666)
      }
    }
  }
}
</script>

<style scoped>
  .box-3{
    width: 100%;
    height: 100%;
    float: left;
    /* background-color: royalblue; */
    margin-top: 40px;
    text-align: left;
  }
  .boxx{
    height: 600px;
  }
  .p2 {
    float: left;
    font-size: 26px;
    width: 100%;
    text-align: left;
    height: 60px;
    border-bottom:1px solid #ccc;
  }
  .box-2{
    width: 100%;
    height: 40px;
    float: left;
  }
  .xg{
    font-size: 16px;
    margin-left: 6px;
  }
  .p1{
    float: left;
  }
  .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }
  .clearfix span{
    float: left;
  }
  .box-card {
    margin: 0 auto;
  }
  .box-1 {
    width: 100%;
    height: 120px;
    /* background-color: aqua; */
  }
</style>
